import React, { MouseEvent, useEffect } from "react";
import classnames from "classnames";

import TreeNode from "./utils";

import "./index.less";

interface OrgTreeProps {
	data: any;
	node?: {
		label?: string;
		expand?: string;
		children?: string;
	};
	horizontal?: boolean;
	collapsable?: boolean;
	expandAll?: boolean;
	renderContent?: (data: any) => React.ReactNode;
	labelWidth?: number;
	labelClassName?: string;
	onClick?: (e: MouseEvent<HTMLDivElement>, nodeData: any) => void;
}

const OrgTree: React.FC<OrgTreeProps> = ({
	data,
	node = { label: "label", expand: "expand", children: "children" },
	horizontal,
	onClick,
	expandAll,
	renderContent = (data: any) => data.label
}) => {
	const handleExpand = (e: MouseEvent<HTMLDivElement>, nodeData: any) => {
		const { children } = nodeData;
		if ("expand" in nodeData) {
			nodeData.expand = !nodeData.expand;
			if (!nodeData.expand && children) {
				collapse(children);
			}
		} else {
			nodeData.expand = true;
		}
	};

	const collapse = (list: any[]) => {
		list.forEach(child => {
			if (child.expand) {
				child.expand = false;
			}
			child.children && collapse(child.children);
		});
	};

	const toggleExpand = (data: any, val: boolean) => {
		if (Array.isArray(data)) {
			data.forEach(item => {
				item.expand = val;
				if (item.children) {
					toggleExpand(item.children, val);
				}
			});
		} else {
			data.expand = val;
			if (data.children) {
				toggleExpand(data.children, val);
			}
		}
	};

	useEffect(() => {
		if (expandAll) toggleExpand(data, true);
	}, [expandAll, data]);
	return (
		<div className="org-tree-container">
			<div className={classnames("org-tree", { horizontal })}>
				<TreeNode data={data} node={node} onExpand={handleExpand} onClick={onClick} renderContent={renderContent} />
			</div>
		</div>
	);
};

export default OrgTree;
